package com.linkoog.devtools.archive.nodes;

import com.google.common.base.MoreObjects;
import com.intellij.ide.projectView.ViewSettings;
import com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode;
import com.intellij.ide.projectView.impl.nodes.PsiFileNode;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Collection;

public class ArchiveBasedPsiNode extends PsiDirectoryNode {

    private final VirtualFile _archiveFile;

    ArchiveBasedPsiNode(Project project, @NotNull PsiDirectory value, VirtualFile jarFile, ViewSettings viewSettings) {
        super(project, value, viewSettings);
        _archiveFile = jarFile;
    }

    @Override
    public Collection<AbstractTreeNode<?>> getChildrenImpl() {
        final PsiManager psiManager = PsiManager.getInstance(getProject());

        VirtualFile[] virtualFiles = _archiveFile.getChildren();
        Collection<AbstractTreeNode<?>> children = new ArrayList<>(virtualFiles.length);
        for (VirtualFile file : virtualFiles) {
            if (!file.isValid()) {
                continue;
            }

            if (file.isDirectory()) {
                final PsiDirectory psiDir = psiManager.findDirectory(file);
                if (psiDir != null) {
                    children.add(new ArchiveBasedPsiNode(getProject(), psiDir, file, getSettings()));
                }
            }
            else {
                final PsiFile psiFile = psiManager.findFile(file);
                if (psiFile != null) {
                    children.add(new PsiFileNode(getProject(), psiFile, getSettings()));
                }
            }
        }

        return children;
    }

    @Override
    public boolean isValid() {
        return true;
    }


    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("_archiveFile", _archiveFile)
                .toString();
    }
}